package com.xiaozhi.controller;

import com.xiaozhi.common.Result;
import com.xiaozhi.utils.HealthAnalysisOptimizer;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 性能监控和优化控制器
 *
 * @author xiaozhi
 * @since 2024-01-15
 */
@RestController
@RequestMapping("/api/performance")
@Tag(name = "性能监控", description = "系统性能监控和优化接口")
public class PerformanceController {

    private static final Logger log = LoggerFactory.getLogger(PerformanceController.class);

    @Autowired
    private HealthAnalysisOptimizer analysisOptimizer;
    
    @Autowired
    private CacheManager cacheManager;


    /**
     * 获取系统性能统计
     */
    @GetMapping("/stats")
    @Operation(summary = "获取系统性能统计")
    public Result<Map<String, Object>> getPerformanceStats() {
        try {
            Map<String, Object> stats = new HashMap<>();
            
            // 获取缓存统计
            Map<String, Object> cacheStats = analysisOptimizer.getCacheStats();
            stats.put("cache", cacheStats);
            
            // 获取JVM内存信息
            Runtime runtime = Runtime.getRuntime();
            Map<String, Object> memoryStats = new HashMap<>();
            memoryStats.put("totalMemory", runtime.totalMemory());
            memoryStats.put("freeMemory", runtime.freeMemory());
            memoryStats.put("usedMemory", runtime.totalMemory() - runtime.freeMemory());
            memoryStats.put("maxMemory", runtime.maxMemory());
            memoryStats.put("usagePercentage", 
                Math.round((double)(runtime.totalMemory() - runtime.freeMemory()) / runtime.maxMemory() * 100));
            stats.put("memory", memoryStats);
            
            // 获取系统信息
            Map<String, Object> systemStats = new HashMap<>();
            systemStats.put("availableProcessors", runtime.availableProcessors());
            systemStats.put("osName", System.getProperty("os.name"));
            systemStats.put("javaVersion", System.getProperty("java.version"));
            stats.put("system", systemStats);
            
            return Result.success(stats);
        } catch (Exception e) {
            log.error("获取性能统计失败", e);
            return Result.error("获取性能统计失败: " + e.getMessage());
        }
    }

    /**
     * 清理过期缓存
     */
    @PostMapping("/cache/cleanup")
    @Operation(summary = "清理过期缓存")
    public Result<String> cleanupCache() {
        try {
            analysisOptimizer.cleanupExpiredCache();
            return Result.success("缓存清理完成");
        } catch (Exception e) {
            log.error("清理缓存失败", e);
            return Result.error("清理缓存失败: " + e.getMessage());
        }
    }

    /**
     * 清空所有缓存
     */
    @PostMapping("/cache/clear")
    @Operation(summary = "清空所有缓存")
    public Result<String> clearAllCache() {
        try {
            analysisOptimizer.clearAllCache();
            
            // 清空Spring缓存
            cacheManager.getCacheNames().forEach(cacheName -> {
                cacheManager.getCache(cacheName).clear();
            });
            
            return Result.success("所有缓存已清空");
        } catch (Exception e) {
            log.error("清空缓存失败", e);
            return Result.error("清空缓存失败: " + e.getMessage());
        }
    }

    /**
     * 获取缓存健康状态
     */
    @GetMapping("/cache/health")
    @Operation(summary = "获取缓存健康状态")
    public Result<Map<String, Object>> getCacheHealth() {
        try {
            Map<String, Object> cacheStats = analysisOptimizer.getCacheStats();
            
            Map<String, Object> health = new HashMap<>();
            
            // 计算缓存使用率
            Integer cacheSize = (Integer) cacheStats.get("cacheSize");
            Integer maxCacheSize = (Integer) cacheStats.get("maxCacheSize");
            
            double usageRate = maxCacheSize > 0 ? (double) cacheSize / maxCacheSize : 0;
            
            // 确定健康状态
            String status;
            String statusText;
            if (usageRate > 0.9) {
                status = "critical";
                statusText = "危险";
            } else if (usageRate > 0.7) {
                status = "warning";
                statusText = "警告";
            } else {
                status = "healthy";
                statusText = "健康";
            }
            
            health.put("status", status);
            health.put("statusText", statusText);
            health.put("usageRate", Math.round(usageRate * 100));
            health.put("cacheSize", cacheSize);
            health.put("maxCacheSize", maxCacheSize);
            
            return Result.success(health);
        } catch (Exception e) {
            log.error("获取缓存健康状态失败", e);
            return Result.error("获取缓存健康状态失败: " + e.getMessage());
        }
    }

    /**
     * 执行性能优化
     */
    @PostMapping("/optimize")
    @Operation(summary = "执行性能优化")
    public Result<Map<String, Object>> optimizePerformance() {
        try {
            long startTime = System.currentTimeMillis();
            
            // 清理过期缓存
            analysisOptimizer.cleanupExpiredCache();
            
            // 执行垃圾回收
            System.gc();
            
            long endTime = System.currentTimeMillis();
            
            Map<String, Object> result = new HashMap<>();
            result.put("optimizationTime", endTime - startTime);
            result.put("message", "性能优化完成");
            
            // 获取优化后的内存信息
            Runtime runtime = Runtime.getRuntime();
            Map<String, Object> memoryAfter = new HashMap<>();
            memoryAfter.put("freeMemory", runtime.freeMemory());
            memoryAfter.put("usedMemory", runtime.totalMemory() - runtime.freeMemory());
            result.put("memoryAfter", memoryAfter);
            
            return Result.success(result);
        } catch (Exception e) {
            log.error("性能优化失败", e);
            return Result.error("性能优化失败: " + e.getMessage());
        }
    }

    /**
     * 获取性能建议
     */
    @GetMapping("/recommendations")
    @Operation(summary = "获取性能优化建议")
    public Result<Map<String, Object>> getPerformanceRecommendations() {
        try {
            Map<String, Object> recommendations = new HashMap<>();
            
            // 获取内存使用情况
            Runtime runtime = Runtime.getRuntime();
            double memoryUsage = (double)(runtime.totalMemory() - runtime.freeMemory()) / runtime.maxMemory();
            
            // 获取缓存使用情况
            Map<String, Object> cacheStats = analysisOptimizer.getCacheStats();
            Integer cacheSize = (Integer) cacheStats.get("cacheSize");
            Integer maxCacheSize = (Integer) cacheStats.get("maxCacheSize");
            double cacheUsage = maxCacheSize > 0 ? (double) cacheSize / maxCacheSize : 0;
            
            // 生成建议
            java.util.List<String> suggestions = new java.util.ArrayList<>();
            
            if (memoryUsage > 0.8) {
                suggestions.add("内存使用率过高，建议增加JVM堆内存大小");
            }
            
            if (cacheUsage > 0.8) {
                suggestions.add("缓存使用率过高，建议清理过期缓存或增加缓存大小");
            }
            
            if (memoryUsage < 0.3 && cacheUsage < 0.3) {
                suggestions.add("系统资源充足，可以考虑增加缓存大小以提高性能");
            }
            
            if (suggestions.isEmpty()) {
                suggestions.add("系统运行良好，无需特殊优化");
            }
            
            recommendations.put("suggestions", suggestions);
            recommendations.put("memoryUsage", Math.round(memoryUsage * 100));
            recommendations.put("cacheUsage", Math.round(cacheUsage * 100));
            
            return Result.success(recommendations);
        } catch (Exception e) {
            log.error("获取性能建议失败", e);
            return Result.error("获取性能建议失败: " + e.getMessage());
        }
    }
}